<template>
  <!-- 商品库存详情查看组件 -->
  <div>
    <div class="flex v-align-c mar-r-30">
      <label><img :src="goodsForm.mainImage" class="t-goods-pic"></label>
      <div class="font-14 pad-l-10 v-align-h height-65">
        <div class="goods-title">
          <div class="line-2">{{ goodsForm.goodsTitle }}</div>
        </div>
        <span class="font-color-6 font-13">[{{ goodsForm.categoryName }}]</span>
      </div>
    </div>
    <div class="mar-t-20 mar-b-10 flex">
      <div style="flex: 2;">
        <span>商品来源：</span>
        <strong>
          <span v-if="goodsForm.goodsSource == 0">总部自营</span>
          <span v-if="goodsForm.goodsSource == 1">{{ goodsForm.supplierName }}</span>
          <span v-if="goodsForm.goodsSource == 2">淘宝联盟</span>
        </strong>
      </div>
      <div style="flex: 2;">
        <span>合计可用库存数：</span>
        <strong class="font-green">{{ goodsForm.stock }}</strong>
      </div>
      <div style="flex: 3;">
        <span>合计占用库存数：</span>
        <strong class="font-red">{{ goodsForm.stockInUse }}</strong>
        <strong class="font-red" v-if="enterpriseConfig.warehouseAuthority == 1">（其中待分仓占用数量<span>&nbsp;{{ waitWarehouseStockInUse }}&nbsp;</span>）</strong>
      </div>
    </div>

    <hr>

    <!-- 库存分布块 -->
    <div class="mar-t-10 mar-b-10">
      <div v-if="headStockForm.length > 0" 
        class="type-border" 
        :class="selectDistributeType == 1 ? 'type-selected' : ''"
        @click="doSeeDetail(1)">

        <strong>总部</strong>
        <div>可用库存：{{ headStockForm[0].remainStock }}</div>
        <div>占用库存：{{ headStockForm[0].stockInUse }}</div>
      </div>

      <div v-if="supplierStockForm.length > 0" 
        class="type-border" 
        :class="selectDistributeType == 2 ? 'type-selected' : ''"
        @click="doSeeDetail(2)">

        <strong>供应商</strong>
        <div>可用库存：{{ supplierStockForm[0].remainStock }}</div>
        <div>占用库存：{{ supplierStockForm[0].stockInUse }}</div>
      </div>

      <div v-if="headWarehouseStockForm.length > 0" 
        class="type-border" 
        :class="selectDistributeType == 3 ? 'type-selected' : ''"
        @click="doSeeDetail(3)">

        <strong>总部仓</strong>
        <div>可用库存：{{ headWarehouseStockForm[0].remainStock }}</div>
        <div>占用库存：{{ headWarehouseStockForm[0].stockInUse }}</div>
      </div>

      <div v-if="supplierWarehouseStockForm.length > 0" 
        class="type-border" 
        :class="selectDistributeType == 4 ? 'type-selected' : ''"
        @click="doSeeDetail(4)">

        <div>供应商仓</div>
        <div>可用库存：{{ supplierWarehouseStockForm[0].remainStock }}</div>
        <div>占用库存：{{ supplierWarehouseStockForm[0].stockInUse }}</div>
      </div>

    </div>

    <!-- 搜索块 -->
    <div class="mar-t-20 mar-b-20">
      <label class="font-14">搜索：</label>
      <el-input @keyup.enter.native="doSearch" v-model.trim="defaultQuery.keyword" placeholder="请输入关键词：规格或仓库名称" class="width-260"></el-input>
      <template v-if="selectDistributeType === 2 || selectDistributeType === 4">
        <label class="mar-l-10 font-14">仓库类型：</label>
        <el-select class="width-160" v-model="defaultQuery.searchWarehouseType" clearable>
          <el-option v-for="(val, key) in dict.warehouseType" :key="key" :label="val" :value="key"/>
        </el-select>
      </template>
      <el-button-group class="mar-l-20">
        <el-button type="primary" @click="doSearch">查询</el-button>
        <el-button plain @click="doResetSearch">重置</el-button>
      </el-button-group>
    </div>

    <div>
      <el-table :data="dataList" ref="table" v-loading="listLoading" element-loading-text="加载中" height=400 show-summary>
        <el-table-column label="规格" prop="skuDetail">
          <template slot-scope="scope">
            <span v-if="scope.row.skuDetail">{{ scope.row.skuDetail }}</span>
            <span v-else>--</span> 
          </template>
        </el-table-column>
        <el-table-column label="所在仓库">
          <template slot-scope="scope">
            <template v-if="scope.row.warehouseId">
              <div>
                <span>类型：</span>
                <span>{{ scope.row.warehouseTypeName }}</span>
              </div>
              <div>
                <span>名称：</span>
                <span>{{ scope.row.warehouseName }}</span>
              </div>
            </template>
            <template v-else>
              <span>--</span> 
            </template>
          </template>
        </el-table-column>
        <el-table-column width="140px" label="可用库存" prop="remainStock"></el-table-column>
        <el-table-column width="140px" label="占用库存" prop="stockInUse"></el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background 
        @size-change="handleSizeChange" 
        @current-change="handleCurrentChange"
        :current-page="searchListQuery.currentPage"
        :page-sizes="[10, 20, 50, 100]" 
        :page-size="searchListQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
  import { statAllStockDistributeByGoodsId, countWaitWarehouseStockInUse } from '@/api/stock/stockDistribute'
  import { pagingStockDetail } from '@/api/warehouse/warehouseGoods'
  import { pagingGoodsSku } from '@/api/goods/goods'
  import { listWarehouseType } from '@/api/warehouse/warehouseInfo'
  import { getByEnterpriseId } from '@/api/user/enterprise'
  import { getDictByGroupName } from '@/api/common/common'

  export default {
    props: {
      showFlag: {
        type: Boolean,
        default() {
          return false
        }
      },
      goodsObj: {
        type: Object
      }
    },
    watch: {
      showFlag(val) {
        if (val) {
          this.init()
        }
      }
    },
    data() {
      return {
        // 查询条件
        searchListQuery: {},
        // 默认查询条件
        defaultQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: '',
          keyword: '',
          searchWarehouseType: ''
        },
        // 数据字典
        dict: {
          warehouseType: {}
        },
        // 商品对象
        goodsForm: {
          mainImage: '',
          goodsTitle: '',
          categoryName: '',
          goodsSource: '',
          supplierName: '',
          stock: '',
          stockInUse: '',
          remainStock: ''
        },
        // 企业配置
        enterpriseConfig: {
          warehouseAuthority: 0
        },
        // 待分仓占用数
        waitWarehouseStockInUse: 0,
        // 总部库存表单
        headStockForm: {},
        // 供应商库存表单
        supplierStockForm: {},
        // 总部仓库库存表单
        headWarehouseStockForm: {},
        // 供应商仓库库存表单
        supplierWarehouseStockForm: {},
        // 当前类型
        selectDistributeType: null,
        listLoading: false,
        total: 0,
        dataList: []
      }
    },
    updated() {
      // 重绘table
      this.$nextTick(() => this.$refs['table'].doLayout())
    },
    created() {
      this.searchListQuery = { ...this.defaultQuery }
      // 获取字典
      getDictByGroupName('WarehouseInfoDTO.warehouseType').then(response => {
        if (response.isError) return
        Object.assign(this.dict.warehouseType, response.data.warehouseType)
      })
      // 获取企业配置
      getByEnterpriseId(this.getEnterpriseId()).then((response) => {
        if (response.isError) return
        Object.assign(this.enterpriseConfig, response.data)
      })
      // 获取第三方仓库类型列表
      listWarehouseType({ enterpriseId: this.getEnterpriseId() }).then(response => {
        const warehouseTypeList = response.data
        warehouseTypeList.forEach(warehouseType => {
          const key = '3-' + warehouseType.warehouseTypeId
          this.dict.warehouseType[key] = '第三方仓-' + warehouseType.warehouseTypeName
        })
      })
      this.init()
    },
    methods: {
      init() {
        const originData = this.$options.data()
        this.goodsForm = originData.goodsForm
        this.dataList = originData.dataList
        this.headStockForm = originData.headStockForm
        this.supplierStockForm = originData.supplierStockForm
        this.headWarehouseStockForm = originData.headWarehouseStockForm
        this.supplierWarehouseStockForm = originData.supplierWarehouseStockForm
        this.selectDistributeType = originData.selectDistributeType
        this.goodsForm = {
          mainImage: this.goodsObj.mainImage,
          goodsTitle: this.goodsObj.title,
          categoryName: this.goodsObj.categoryName,
          goodsSource: this.goodsObj.goodsSource,
          supplierName: this.goodsObj.supplierName,
          stock: this.goodsObj.stock,
          stockInUse: this.goodsObj.stockInUse,
          remainStock: this.goodsObj.remainStock
        }
        this.listLoading = true
        statAllStockDistributeByGoodsId(this.goodsObj.goodsId).then(response => {
          if (response.isError) return
          const list = response.data
          // 分布类型 1：总部 2：供应商 3：总部仓 4：供应商仓
          this.headStockForm = list.filter(item => item.distributeType === 1)
          this.supplierStockForm = list.filter(item => item.distributeType === 2)
          this.headWarehouseStockForm = list.filter(item => item.distributeType === 3)
          this.supplierWarehouseStockForm = list.filter(item => item.distributeType === 4)
          this.doSeeDetail(list[0].distributeType)
          if (this.enterpriseConfig.warehouseAuthority === 1) {
            countWaitWarehouseStockInUse(this.goodsObj.goodsId).then(response => {
              if (response.isError) return
              this.waitWarehouseStockInUse = response.data
            })
          }
        })
      },
      // 查看库存详情
      doSeeDetail(distributeType) {
        if (!distributeType || this.selectDistributeType === distributeType) {
          return
        }
        this.selectDistributeType = distributeType
        this.doResetSearch()
      },
      // 列表查询
      initList() {
        this.listLoading = true
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.goodsId = this.goodsObj.goodsId
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        if (this.selectDistributeType === 3 || this.selectDistributeType === 4) {
          var wtArray = this.searchListQuery.searchWarehouseType.split('-')
          this.searchListQuery.warehouseType = wtArray[0]
          this.searchListQuery.warehouseTypeId = wtArray[1]
          this.searchListQuery.warehouseSource = this.selectDistributeType === 3 ? 1 : 2
          pagingStockDetail(this.searchListQuery).then(response => {
            this.listLoading = false
            if (response.isError) return
            this.dataList = response.data.records
            this.total = response.data.total
          })
        } else {
          this.searchListQuery.skuDetial = this.searchListQuery.keyword
          pagingGoodsSku(this.searchListQuery).then(response => {
            this.listLoading = false
            if (response.isError) return
            this.dataList = response.data.records
            this.total = response.data.total
          })
        }
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.defaultQuery = originData.defaultQuery
        this.initList()
      },
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      },
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .goods-title {
    color: #155bd4;
    line-height: 1.2;
  }
  .type-border {
    border: #ccc 1px solid;
    border-radius: 5%;
    padding: 10px 15px;
    display: inline-block;
    margin-right: 20px;
    cursor: pointer;
    strong {
      font-size: 16px;
    }
  }
  .type-border:hover,
  .type-selected {
    border: dodgerblue 1px solid;
    color: dodgerblue;
  }
</style>